<template>
  <div class="common-chart" :style="chartStyle" ref="chartWrapper">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'CommonChart',
  props: {
    config: {
      type: Object,
      required: true,
      default: () => ({
        width: '100%',
        height: '300px',
        backgroundColor: '#ffffff',
        option: {
          title: {
            text: '图表标题'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [150, 230, 224, 218, 135, 147, 260],
            type: 'line'
          }]
        }
      })
    },
    apiObj: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      chart: null,
      refreshTimer: null
    }
  },
  computed: {
    chartStyle() {
      return {
        width: this.config.width,
        height: this.config.height,
        backgroundColor: this.config.backgroundColor
      }
    }
  },
  watch: {
    'config.option': {
      handler(newVal) {
        this.updateChart()
      },
      deep: true
    },
    'config.width'() {
      this.handleResize()
    },
    'config.height'() {
      this.handleResize()
    },
    apiObj: {
      handler(newVal) {
        if (newVal) {
          this.fetchData();
          this.setupAutoRefresh();
        } else {
          this.clearRefreshTimer();
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    
    // 如果有 apiObj，初始化时获取数据
    if (this.apiObj) {
      this.fetchData();
      this.setupAutoRefresh();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart?.dispose();
    this.clearRefreshTimer();
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },
    updateChart() {
      if (!this.chart) return;
      
      // 根据图表类型设置不同的 grid 配置
      let option = { ...this.config.option };
      
      if (option.series[0].type !== 'pie') {
        option = {
          ...option,
          grid: {
            left: '2%',      // 左边距
            right: '5%',      // 右边距
            bottom: '10%',    // 底部边距
            top: '15%',       // 顶部边距
            containLabel: true // 确保刻度标签在容器内
          }
        };
      }
      
      this.chart.setOption(option, true);
    },
    handleResize() {
      this.$nextTick(() => {
        const wrapper = this.$refs.chartWrapper;
        if (wrapper && this.chart) {
          // 获取容器的实际尺寸
          const { width, height } = wrapper.getBoundingClientRect();
          
          // 调整图表尺寸
          this.chart.resize();

          // 根据容器尺寸动态调整 grid 配置
          if (this.config.option.series[0].type !== 'pie') {
            const newOption = {
              ...this.config.option,
              grid: {
                ...this.config.option.grid,
                left: '2%',      // 左边距
                right: '5%',      // 右边距
                bottom: '10%',    // 底部边距
                top: '15%',       // 顶部边距
                containLabel: true // 确保刻度标签在容器内
              }
            };
            this.chart.setOption(newOption);
          }
        }
      });
    },
    async fetchData() {
      if (!this.apiObj?.url) return;
      
      try {
        const response = await fetch(this.apiObj.url, {
          method: this.apiObj.method || 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        
        // 使用路径获取数据
        const categories = this.getValueByPath(data, this.apiObj.mapping.categories) || [];
        const series = this.getValueByPath(data, this.apiObj.mapping.series) || [];

        // 更新图表配置
        const newOption = { ...this.config.option };
        
        if (this.config.option.series[0].type !== 'pie') {
          newOption.xAxis.data = categories;
          newOption.series = series.map(item => ({
            ...item,
            type: this.config.option.series[0].type
          }));
        } else {
          const firstSeries = series[0] || { data: [] };
          newOption.series[0].data = firstSeries.data.map((value, index) => ({
            name: categories[index] || `数据${index + 1}`,
            value
          }));
        }

        this.$emit('update:config', {
          ...this.config,
          option: newOption
        });
      } catch (error) {
        console.error('获取远程数据失败:', error);
      }
    },
    setupAutoRefresh() {
      this.clearRefreshTimer();
      if (this.apiObj?.autoRefresh && this.apiObj.refreshInterval > 0) {
        this.refreshTimer = setInterval(() => {
          this.fetchData();
        }, this.apiObj.refreshInterval * 1000);
      }
    },
    clearRefreshTimer() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    getValueByPath(obj, path) {
      return path.split('.').reduce((acc, part) => {
        return acc && acc[part];
      }, obj);
    }
  }
}
</script>

<style scoped>
.common-chart {
  width: 100%;
  height: 100%;
  background: transparent !important;
  border: none !important;
}

.chart-container {
  width: 100%;
  height: 100%;
}

:deep(.echarts) {
  background: transparent !important;
  border: none !important;
}
</style> 